<template>
	<view>
		<!-- 以下是列表 -->
		<view class="uni-container">
			<uni-table ref="tableRef" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<!-- <uni-th width="100%" align="center">ID</uni-th> -->
					<uni-th width="100%" align="left" :sortable="true" @sort-change="sortChangeName">項目名称</uni-th>
					<uni-th width="100%" align="center">鏡像地址</uni-th>
					<uni-th width="100%" align="center">更新時間</uni-th>
					<uni-th width="100%" align="center">操作</uni-th>
					<!-- <uni-th width="200px" align="center" :sortable="true">分支</uni-th> -->
				</uni-tr>
				<uni-tr v-for="(item, index) in sortedTableData" :key="index">
					<!-- <uni-td>{{ item.date }}</uni-td> -->
					<uni-td>
						<view class="name">{{ item.deployname }}</view>
					</uni-td>
					<uni-td>
						<view class="name">{{ item.image }}</view>
					</uni-td>
					<uni-td>
						<view class="name">{{ item.date }}</view>
					</uni-td>
					<uni-td>
						<view class="button-group-del">
							<!-- <button size="mini" type="warn" @click="delRedisCache(item.deployname)">刪除</button> -->
							<button class="button popup-error" @click="dialogToggle('error', item.deployname)">
								<text class="button-text error-text">刪除</text>
							</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="button-group">
		<!-- #endif -->
			<a>数量: {{selectionCount}}</a>
			<button @click="getTableData">刷新</button>
			<button :disabled="this.multiSelect.length === 0" @click="updateSrv">更新服務</button>
		<!-- #ifdef MP-WEIXIN -->
		</view>
		<!-- #endif -->

	</view>

	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="同意" title="警告"
				:content="`删除  ${delSrvList}  服务待更新缓存`" @confirm="delRedisCache"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				apiUrl: "",
				goApiUrl: "",
				tableData: [],
				tableRef: null,
				selectedIndexs: [],
				multiSelect: [],
				// 排序字段和顺序
				sortKey: '', // 当前排序字段
				sortOrder: '', // asc | desc
				// 存储排序后的数据（可用于模板和其他方法）
				sortedTableData: [],
				// 使用限流接口更新鏡像時的環境參數
				updateSrvMethParams: {
					cluster: "",
					namespace: ""
				},
				// 待删除列表
				delSrvList: [],
				selectionCount: null,
			}
		},
		created() {
			this.sortedTableData = [...this.tableData] // 初始化为原始数据
		},
		watch: {
			// 监听排序字段或顺序变化
			sortKey: {
				handler() {
					this.applySorting();
				}
			},
			sortOrder: {
				handler() {
					this.applySorting();
					this.clearSelected();
				}
			},
			// tableData 有變化時也重新排序刷新數據，不然不會自動刷新
			tableData: {
				handler() {
					this.applySorting();
					this.clearSelected();
				}
			}
		},
		methods: {
			getTableData() {
				uni.request({
					// url: 'https://ops.edccmss.cn/api-go/v1/public/clientGo/podinformer',
					url: this.apiUrl + '/apis/jenkins/ManualUpdate/',
					method: 'GET',
					// data: this.podinformerDate,
					// sslVerify: false,
					success: (res) => {
						console.log("res.data: ", res.data)
						if (res.data.data != null) {
							this.tableData = res.data.data
							this.sortChangeName({
								order: 'ascending'
							})
						}

					},
					fail: (res) => {
						console.log(res.errMsg)
					},
					complete: (res) => {
						console.log('complete')
					}
				});
			},
			// 多选
			selectionChange(e) {
				// console.log(e.detail.index)
				console.log("selectionChange: ", e)
				console.log("tableRef: ", this.$refs.tableRef)
				this.selectedIndexs = e.detail.index
				this.selectionCount = this.selectedIndexs.length
				this.selectionData()
			},
			// 多選后的實際數據
			selectionData() {
				// 先清空數組
				this.multiSelect = []
				for (const item of this.selectedIndexs) {
					this.multiSelect.push(this.sortedTableData[item]);
					// console.log("selectedIndexs: ", this.resData.results[item]);
				}
				// this.multijobData.BRANCH = this.baseFormData.branch
				// this.multijobData.UPDATE = this.baseFormData.update
				console.log("最終提交數據：", this.multiSelect)
			},
			// 排序時觸發事件 deployname 字段
			sortChangeName(e) {
				console.log("sortChange:", e)
				const {
					order
				} = e
				this.sortKey = 'deployname'
				this.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''

				console.log('排序字段:', this.sortKey, '排序顺序:', this.sortOrder)

				// 触发数据重新计算（computed 会自动响应）
			},
			// 执行排序逻辑，并更新 data 中的 sortedTableData
			applySorting() {
				const {
					sortKey,
					sortOrder,
					tableData
				} = this

				if (!sortKey || !sortOrder) {
					// 如果没有排序条件，恢复为原始数据
					this.sortedTableData = tableData.slice()
					return
				}

				// 执行排序
				const sorted = tableData.slice().sort((a, b) => {
					const valA = a[sortKey]
					const valB = b[sortKey]
					let res = 0
					if (valA < valB) res = -1
					else if (valA > valB) res = 1
					else res = 0

					return sortOrder === 'asc' ? res : -res
				})

				// 赋值给 data 变量，可在模板和其他地方使用
				this.sortedTableData = sorted
			},
			// 更新服務
			updateSrv() {
				const delSrvList = []
				for (var index = 0; index < this.multiSelect.length; index++) {
					var element = this.multiSelect[index];
					delSrvList.push(element.deployname)
					this.updateSrvMeth(element.deployname, element.image)
				}
				this.deleteRedisSrvMeth(delSrvList)
			},
			// 更新服務的方法
			updateSrvMeth(deployName, imageUrl) {
				uni.request({
					url: this.goApiUrl + '/api-go/v1/public/clientGo/deployment',
					method: 'POST',
					data: {
						"cluster": this.updateSrvMethParams.cluster,
						"namespacename": this.updateSrvMethParams.namespace,
						"deployname": deployName,
						"image": imageUrl
					},
					// sslVerify: false,
					success: (res) => {
						console.log("updateSrvMeth: ", res.data)
					},
					fail: (res) => {
						console.log("updateSrvMeth_fail:", res.errMsg)
					},
					complete: (res) => {
						console.log('complete')
					}
				});
			},
			// 執行更新后，刪除緩存裡面服務的方法
			deleteRedisSrvMeth(delList) {
				uni.request({
					url: this.apiUrl + '/apis/jenkins/ManualUpdate/getAndDel/',
					method: 'PUT',
					data: delList,
					// sslVerify: false,
					success: (res) => {
						// console.log("deleteRedisSrvMeth: ", res.data)
						this.messageToggle(res.data.type, "")
						this.getTableData()
					},
					fail: (res) => {
						console.log(res.errMsg)
					},
					complete: (res) => {
						console.log('complete')
					}
				});
			},
			// 消息提示框
			messageToggle(type, msg) {
				uni.showToast({
					title: msg,
					icon: type === 'success' ? 'success' : 'error',
					duration: 2000,
					mask: false
				})
			},
			// 清除選擇框
			clearSelected() {
				this.$refs.tableRef.clearSelection()
			},
			// 刪除不需要更新服務的 redis 緩存條目
			delRedisCache() {
				console.log("待刪除條目：", this.delSrvList)
				this.deleteRedisSrvMeth(this.delSrvList)
			},
			// 关闭弹窗
			dialogClose() {
				console.log('点击关闭')
			},
			// 删除弹窗
			dialogToggle(type, delSrv) {
				this.delSrvList = [delSrv]
				this.msgType = type
				this.$refs.alertDialog.open()
			},
		},
		mounted() {
			// #ifdef MP-WEIXIN
			this.apiUrl = import.meta.env.VITE_PYTHON_APIURL_WX
			this.goApiUrl = import.meta.env.VITE_GO_APIURL_WX
			// #endif
			// #ifdef WEB
			this.apiUrl = import.meta.env.VITE_PYTHON_APIURL
			this.goApiUrl = import.meta.env.VITE_GO_APIURL
			// #endif

			this.updateSrvMethParams.cluster = import.meta.env.VITE_GO_DEPLOYMENT_CLUSTER
			this.updateSrvMethParams.namespace = import.meta.env.VITE_GO_DEPLOYMENT_NAMESPACE

			this.getTableData()
			console.log("gourl:", this.goApiUrl)
		},
	}
</script>

<style lang="scss">
	/* #ifndef H5 */
	/* page {
		padding-top: 85px;
	} */
	/* #endif */
	.uni-group {
		display: flex;
		align-items: center;
	}



	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.button-group-del {
		margin-top: 1px;
		display: flex;
		justify-content: space-around;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}

	.button {
		@include flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		height: 35px;
		margin: 0 5px;
		border-radius: 5px;
	}


	.button-text {
		color: #fff;
		font-size: 12px;
	}

	.popup-error {
		color: #fff;
		background-color: #fde2e2;
	}

	.error-text {
		color: #f56c6c;
	}
</style>